package br.pucrio.inf.aaaong.models.components;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.ComponentFactory;
import br.pucrio.inf.aaaong.utils.ExceptionLogger;

@Component
@ApplicationScoped
public class ConnectionCreator implements ComponentFactory<Connection> {

	private static final String DATABASE_USER = "postgres";
	private static final String DATABASE_PASS = "senha123./4";
	private static final String DATABASE_NAME = "projeto_aaa";
	private Connection connection;
	
	@Override
	public Connection getInstance() {
		if  (!connectionIsValid()) {
			this.connection = getNewConnection();
		}
		return this.connection;
	}

	private boolean connectionIsValid() {
		try {
			return connection != null && connection.isValid(3);
		} catch (SQLException e) {
			return false;
		}
	}

	private Connection getNewConnection() {
		try{
			Class.forName("org.postgresql.Driver");     
		}
		catch(ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		
		int tries = 0;
		while (tries < 3) {
			try {
				String url = "jdbc:postgresql://localhost:5432/" + DATABASE_NAME;
				Connection con = DriverManager.getConnection(url, DATABASE_USER, DATABASE_PASS);
				con.setAutoCommit(false);
				return con;
			} catch (SQLException e) {
				ExceptionLogger.log(e);
				tries++;
			}
		}
		throw new RuntimeException("Connection with Database couldn't be opened.");
	}

}
